package com.sergio.accounting.util;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * 用户上下文工具类
 * 用于从JWT token中获取当前用户信息
 */
@Slf4j
@Component
public class UserContextUtil {

    private static JwtUtil jwtUtil;

    @Autowired
    public void setJwtUtil(JwtUtil jwtUtil) {
        UserContextUtil.jwtUtil = jwtUtil;
    }

    /**
     * 获取当前登录用户的ID
     */
    public static Long getCurrentUserId() {
        try {
            // 从当前请求中获取Authorization头
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String authorization = request.getHeader("Authorization");
                
                log.debug("Authorization头: {}", authorization);
                
                if (authorization != null && authorization.startsWith("Bearer ")) {
                    String token = authorization.substring(7);
                    log.debug("提取的JWT token: {}", token.substring(0, Math.min(token.length(), 20)) + "...");
                    
                    try {
                        // 直接从JWT中提取用户ID
                        Long userId = jwtUtil.extractUserId(token);
                        if (userId != null) {
                            log.debug("从JWT中提取到用户ID: {}", userId);
                            return userId;
                        } else {
                            log.warn("JWT中未找到用户ID");
                        }
                    } catch (Exception e) {
                        log.error("解析JWT token失败: {}", e.getMessage());
                    }
                } else {
                    log.warn("Authorization头格式不正确或为空");
                }
            } else {
                log.warn("无法获取当前请求上下文");
            }
            
            log.warn("无法从JWT中提取用户ID");
            return null;
        } catch (Exception e) {
            log.error("获取当前用户ID失败: {}", e.getMessage(), e);
            return null;
        }
    }

    /**
     * 获取当前登录用户的用户名
     */
    public static String getCurrentUsername() {
        try {
            // 从当前请求中获取Authorization头
            ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
            if (attributes != null) {
                HttpServletRequest request = attributes.getRequest();
                String authorization = request.getHeader("Authorization");
                
                if (authorization != null && authorization.startsWith("Bearer ")) {
                    String token = authorization.substring(7);
                    // 直接从JWT中提取用户名
                    String username = jwtUtil.extractUsername(token);
                    if (username != null) {
                        log.debug("从JWT中提取到用户名: {}", username);
                        return username;
                    }
                }
            }
            
            log.warn("无法从JWT中提取用户名");
            return null;
        } catch (Exception e) {
            log.error("获取当前用户名失败: {}", e.getMessage());
            return null;
        }
    }

    /**
     * 检查当前用户是否已登录
     */
    public static boolean isAuthenticated() {
        try {
            Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
            return authentication != null && authentication.isAuthenticated();
        } catch (Exception e) {
            log.error("检查用户认证状态失败: {}", e.getMessage());
            return false;
        }
    }

    /**
     * 获取当前用户的完整信息（通过用户名查询数据库）
     */
    public static com.sergio.accounting.entity.User getCurrentUser() {
        try {
            String username = getCurrentUsername();
            if (username != null) {
                // 这里需要注入UserService，但静态方法无法直接注入
                // 建议使用非静态方法或者通过其他方式获取
                log.debug("当前用户名: {}", username);
                return null; // 临时返回null
            }
        } catch (Exception e) {
            log.error("获取当前用户信息失败: {}", e.getMessage());
        }
        return null;
    }
}
